package com.bdit.ydcb.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationConfiguration.LocationMode;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.navi.BaiduMapAppNotSupportNaviException;
import com.baidu.mapapi.utils.OpenClientUtil;
import com.baidu.mapapi.utils.route.BaiduMapRoutePlan;
import com.baidu.mapapi.utils.route.RouteParaOption;
import com.bdit.ydcb.R;
import com.bdit.ydcb.callback.JsonCallback;
import com.bdit.ydcb.model.Page;
import com.bdit.ydcb.model.WaterUser;
import com.bdit.ydcb.utils.Urls;
import com.bumptech.glide.Glide;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.vise.log.ViseLog;

import java.util.List;


/**
 * 用来展示定位SDK与地图结合显示位置
 *
 */
public class MapActivity extends Activity implements SensorEventListener {

	// 定位相关
	LocationClient mLocClient;
	public MyLocationListenner myListener = new MyLocationListenner();
	private LocationMode mCurrentMode;
	BitmapDescriptor mCurrentMarker;
	private SensorManager mSensorManager;
	private Double lastX = 0.0;
	private int mCurrentDirection = 0;
	private double mCurrentLat = 0.0;
	private double mCurrentLon = 0.0;
	private float mCurrentAccracy;

	MapView mMapView;
	BaiduMap mBaiduMap;

	// UI相关
	Button requestLocButton;
	boolean isFirstLoc = true; // 是否首次定位
	private MyLocationData locData;
	private static final String TAG = "MapActivity";
	/**
	 * 详细信息的 布局
	 */
	private RelativeLayout mMarkerInfoLy;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		SDKInitializer.initialize(getApplicationContext());
		setContentView(R.layout.activity_map);
		requestLocButton = (Button) findViewById(R.id.button1);
		mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);// 获取传感器管理服务
		mCurrentMode = LocationMode.NORMAL;
		requestLocButton.setText("普通");
		mMarkerInfoLy = (RelativeLayout) findViewById(R.id.id_marker_info);
		View.OnClickListener btnClickListener = new View.OnClickListener() {
			public void onClick(View v) {
				switch (mCurrentMode) {
				case NORMAL:
					requestLocButton.setText("跟随");
					mCurrentMode = LocationMode.FOLLOWING;
					mBaiduMap.setMyLocationConfiguration(
							new MyLocationConfiguration(mCurrentMode, true, mCurrentMarker));
					MapStatus.Builder builder = new MapStatus.Builder();
					builder.overlook(0);
					mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
					break;
				case COMPASS:
					requestLocButton.setText("普通");
					mCurrentMode = LocationMode.NORMAL;
					mBaiduMap.setMyLocationConfiguration(
							new MyLocationConfiguration(mCurrentMode, true, mCurrentMarker));
					MapStatus.Builder builder1 = new MapStatus.Builder();
					builder1.overlook(0);
					mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder1.build()));
					break;
				case FOLLOWING:
					requestLocButton.setText("罗盘");
					mCurrentMode = LocationMode.COMPASS;
					mBaiduMap.setMyLocationConfiguration(
							new MyLocationConfiguration(mCurrentMode, true, mCurrentMarker));
					break;
				default:
					break;
				}
			}
		};
		
		requestLocButton.setOnClickListener(btnClickListener);



		// 地图初始化
		mMapView = (MapView) findViewById(R.id.bmapView);
		mBaiduMap = mMapView.getMap();
		// 开启定位图层
		mBaiduMap.setMyLocationEnabled(true);

		mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
			@Override
			public void onMapClick(LatLng latLng) {
				//点击地图某个位置获取经纬度latLng.latitude、latLng.longitude
				ViseLog.d(TAG, "onMapClick: "+latLng.latitude + "," + latLng.longitude);
				mMarkerInfoLy.setVisibility(View.GONE);
			}

			@Override
			public boolean onMapPoiClick(MapPoi mapPoi) {
				//点击地图上的poi图标获取描述信息：mapPoi.getName()，经纬度：mapPoi.getPosition()
				return false;
			}
		});

		// 定位初始化
		mLocClient = new LocationClient(this);
		mLocClient.registerLocationListener(myListener);
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true); // 打开gps
		option.setCoorType("bd09ll"); // 设置坐标类型
		option.setScanSpan(1000);
		//option.setLocationMode(LocationClientOption.LocationMode.Device_Sensors);
		//option.setNeedDeviceDirect(true);
		mLocClient.setLocOption(option);
		mLocClient.start();
		showPoint();
		
	}
	/**
	 * 启动百度地图导航(Native)
	 */
	public void startNavi(LatLng latLng) {
		LatLng pt1 = new LatLng(mCurrentLat, mCurrentLon);

		// 构建 导航参数
		/*NaviParaOption para = new NaviParaOption()
				.startPoint(pt1).endPoint(latLng);*/
		RouteParaOption para = new RouteParaOption()
				.startPoint(pt1)
            .endPoint(latLng);
		try {
			//BaiduMapNavigation.openBaiduMapNavi(para, this);
			BaiduMapRoutePlan.openBaiduMapDrivingRoute(para, this);
		} catch (BaiduMapAppNotSupportNaviException e) {
			e.printStackTrace();
			showDialog();
		}

	}
	public void showPoint(){
		// 定义点聚合管理类ClusterManager
		//mClusterManager = new ClusterManager<MyItem>(this, mBaiduMap);
		addMarkers();
		// 设置地图监听，当地图状态发生改变时，进行点聚合运算
//		mBaiduMap.setOnMapStatusChangeListener(mClusterManager);
//		// 设置maker点击时的响应
//		mBaiduMap.setOnMarkerClickListener(mClusterManager);
//
//		mClusterManager.setOnClusterClickListener(new ClusterManager.OnClusterClickListener<MyItem>() {
//			@Override
//			public boolean onClusterClick(Cluster<MyItem> cluster) {
//				Toast.makeText(MapActivity.this,
//						"有" + cluster.getSize() + "个水表", Toast.LENGTH_SHORT).show();
//
//				return false;
//			}
//		});
//		mClusterManager.setOnClusterItemClickListener(new ClusterManager.OnClusterItemClickListener<MyItem>() {
//			@Override
//			public boolean onClusterItemClick(MyItem item) {
//				startNavi(item.getPosition());
//				return false;
//			}
//		});
	}
	/**
	 * 向地图添加Marker点
	 */
	public void addMarkers() {
		OkGo.<Page<List<WaterUser>>>get(Urls.GET_WATERUSER_ALL_URL)
				.tag(this)
				.execute(new JsonCallback<Page<List<WaterUser>>>() {
					@Override
					public void onSuccess(Response<Page<List<WaterUser>>> response) {
						StringBuilder sb;
						/*Call call = response.getRawCall();
						if (call != null) {
							Log.d(TAG,"请求成功  请求方式：" + call.request().method() + "\n" + "url：" + call.request().url());
						}*/
						Page<List<WaterUser>> page = response.body();

						List<WaterUser> list=page.getList();
						ViseLog.d(list);
						MarkerOptions option = null;
						Marker marker = null;
						for(WaterUser wu:list){
							if(wu.getLat()>0.0&&wu.getLng()>0.0){
								LatLng latlng = new LatLng(wu.getLat(), wu.getLng());
								View markerView = LayoutInflater.from(MapActivity.this).inflate(R.layout.user_marker, null);
								TextView user_name = (TextView) markerView.findViewById(R.id.user_text);
								user_name.setText(wu.getUserName());
								option = new MarkerOptions().position(latlng)
										.icon(BitmapDescriptorFactory.fromView(markerView));
								//option.animateType(MarkerOptions.MarkerAnimateType.drop);
								marker = (Marker) (mBaiduMap.addOverlay(option));
								Bundle bundle = new Bundle();
								bundle.putSerializable("info",wu);
								marker.setExtraInfo(bundle);
								mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
									@Override
									public boolean onMarkerClick(Marker marker) {
										WaterUser wu = (WaterUser) marker.getExtraInfo().get("info");
										mMarkerInfoLy.setVisibility(View.VISIBLE);
										popupInfo(mMarkerInfoLy, wu);
										return true;
									}
								});
							}
						}
					}
				});



    }
	protected void popupInfo(RelativeLayout mMarkerLy,WaterUser wu)
	{
		ViewHolder viewHolder = null;
		if (mMarkerLy.getTag() == null)
		{
			viewHolder = new ViewHolder();
			viewHolder.infoImg = (ImageView) mMarkerLy
					.findViewById(R.id.info_img);
			viewHolder.info_current_num = (TextView) mMarkerLy
					.findViewById(R.id.info_current_num);

			mMarkerLy.setTag(viewHolder);
		}
		viewHolder = (ViewHolder) mMarkerLy.getTag();
		Glide.with(MapActivity.this)
				.load(Urls.ORIGINAL_SERVER+wu.getPic())
				.placeholder(R.drawable.loading3)
				.thumbnail(0.5f)
				.error(R.drawable.load_error)
				.into(viewHolder.infoImg);
		viewHolder.info_current_num.setText(wu.getCurrentNum().toString());

	}
	@Override
	public void onSensorChanged(SensorEvent sensorEvent) {
		//每次方向改变，重新给地图设置定位数据，用上一次onReceiveLocation得到的经纬度、精度
		double x = sensorEvent.values[SensorManager.DATA_X];
		if (Math.abs(x - lastX) > 1.0) {// 方向改变大于1度才设置，以免地图上的箭头转动过于频繁
			mCurrentDirection = (int) x;
			locData = new MyLocationData.Builder().accuracy(mCurrentAccracy)
					// 此处设置开发者获取到的方向信息，顺时针0-360
					.direction(mCurrentDirection).latitude(mCurrentLat).longitude(mCurrentLon).build();
			mBaiduMap.setMyLocationData(locData);
			
		}
		lastX = x;

	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int i) {

	}

	/**
	 * 定位SDK监听函数
	 */
	public class MyLocationListenner implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			// map view 销毁后不在处理新接收的位置
			if (location == null || mMapView == null) {
				return;
			}
			mCurrentLat = location.getLatitude();
			mCurrentLon = location.getLongitude();
			mCurrentAccracy = location.getRadius();
			locData = new MyLocationData.Builder().accuracy(location.getRadius())
					// 此处设置开发者获取到的方向信息，顺时针0-360
					.direction(mCurrentDirection).latitude(location.getLatitude()).longitude(location.getLongitude()).build();
			mBaiduMap.setMyLocationData(locData);
			if (isFirstLoc) {
				isFirstLoc = false;
				LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
				MapStatus.Builder builder = new MapStatus.Builder();
				builder.target(ll).zoom(15.0f);
				mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
			}
		}

		@Override
		public void onConnectHotSpotMessage(String s, int i) {

		}

	}

	@Override
	protected void onPause() {
		mMapView.onPause();
		super.onPause();
	}

	@Override
	protected void onResume() {
		mMapView.onResume();
		super.onResume();
		// 为系统的方向传感器注册监听器
		mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
				SensorManager.SENSOR_DELAY_UI);
	}

	@Override
	protected void onStop() {
		// 取消注册传感器监听
		mSensorManager.unregisterListener(this);
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		// 退出时销毁定位
		mLocClient.unRegisterLocationListener(myListener);
		mLocClient.stop();
		// 关闭定位图层
		mBaiduMap.setMyLocationEnabled(false);
		mMapView.onDestroy();
		mMapView = null;
		super.onDestroy();
	}

	/**
	 * 提示未安装百度地图app或app版本过低
	 */
	public void showDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("您尚未安装百度地图app或app版本过低，点击确认安装？");
		builder.setTitle("提示");
		builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				OpenClientUtil.getLatestBaiduMapApp(MapActivity.this);
			}
		});

		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});

		builder.create().show();

	}
	/**
	 * 复用弹出面板mMarkerLy的控件
	 *
	 * @author zhy
	 *
	 */
	private class ViewHolder
	{
		ImageView infoImg;
		TextView info_current_num;

	}


}
